package org.dioib.practice.controller;


import org.dioib.practice.common.Result;
import org.dioib.practice.common.constant.StatusCode;
import org.dioib.practice.model.SysUser;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/SysUsers")
public class UserController {

    private List<SysUser> sysUsers = new ArrayList<>();
    private Long nextId = 1L;

    // 获取所有用户
    @GetMapping
    public Result<List<SysUser>> getAllSysUsers() {
        return Result.success(sysUsers);
    }

    // 根据ID获取单个用户
    @GetMapping("/{id}")
    public Result<SysUser> getSysUserById(@PathVariable Long id) {
        Optional<SysUser> sysUser = sysUsers.stream()
                .filter(u -> u.getId().equals(id))
                .findFirst();
        return sysUser.map(Result::success)
                .orElse(Result.error(StatusCode.NOT_FOUND, "用户不存在"));
    }

    // 创建新用户
    @PostMapping
    public Result<SysUser> createSysUser(@RequestBody SysUser sysUser) {
        sysUser.setId(nextId++);
        sysUsers.add(sysUser);
        return Result.success(sysUser);
    }

    // 更新用户信息
    @PutMapping("/{id}")
    public Result<SysUser> updateSysUser(@PathVariable Long id, @RequestBody SysUser sysUserDetails) {
        Optional<SysUser> sysUserOpt = sysUsers.stream()
                .filter(u -> u.getId().equals(id))
                .findFirst();
        if (sysUserOpt.isPresent()) {
            SysUser SysUser = sysUserOpt.get();
            SysUser.setFirstName(sysUserDetails.getFirstName());
            SysUser.setEmail(sysUserDetails.getEmail());
            return Result.success(sysUserDetails);
        }
        return Result.error(StatusCode.NOT_FOUND, "用户不存在");
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public Result<String> deleteSysUser(@PathVariable Long id) {
        boolean removed = sysUsers.removeIf(u -> u.getId().equals(id));
        return removed ? Result.success("删除成功") : Result.error(StatusCode.NOT_FOUND, "用户不存在");
    }
}
